<template>
    <div class="payment-page">
        <van-nav-bar title="订单支付" left-arrow @click-left="$router.back" />

        <div class="payment-info">
            <!-- 订单摘要 -->
            <div class="order-summary card">
                <div class="order-id">订单号: {{ order.id }}</div>
                <div class="order-amount">支付金额: <span class="amount">¥{{ orderAmount }}</span></div>
            </div>

            <!-- 支付方式选择 -->
            <div class="payment-methods card">
                <div class="method-title">选择支付方式</div>
                <van-radio-group v-model="selectedMethod">
                    <van-radio name="wechat" shape="square">
                        <div class="payment-option">
                            <span>微信支付</span>
                        </div>
                    </van-radio>
                    <van-radio name="alipay" shape="square">
                        <div class="payment-option">
                            <span>支付宝</span>
                        </div>
                    </van-radio>
                    <van-radio name="card" shape="square">
                        <div class="payment-option">
                            <span>银行卡支付</span>
                        </div>
                    </van-radio>
                </van-radio-group>
            </div>

            <!-- 支付按钮 -->
            <van-button type="primary" size="large" @click="processPayment" class="confirm-payment-btn"
                :loading="isPaying" :disabled="isPaying || order.status === 1">
                {{ order.status === 1 ? '已支付' : '确认支付' }}
            </van-button>

            <!-- 支付成功状态 -->
            <div v-if="paymentSuccess" class="payment-success-message card">
                <div class="success-icon">
                    <van-icon name="success" size="60" color="#07c160" />
                </div>
                <div class="success-text">支付成功！</div>
                <div class="success-details">
                    <div class="detail-item">
                        <span class="label">支付方式:</span>
                        <span class="value">{{ paymentMethodText }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">支付时间:</span>
                        <span class="value">{{ formattedPaymentTime }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">订单号:</span>
                        <span class="value">{{ order.id }}</span>
                    </div>
                </div>

                <div class="action-buttons">
                    <van-button type="default" size="large" @click="goToOrderList" class="back-btn">
                        返回订单列表
                    </van-button>
                    <van-button type="primary" size="large" @click="goToHome" class="home-btn">
                        返回首页
                    </van-button>
                </div>
            </div>

            <!-- 商品详情 -->
            <div v-if="order.products && order.products.length > 0" class="products-preview card">
                <div class="preview-title">商品详情</div>
                <div class="product-item" v-for="(product, index) in order.products" :key="index">
                    <img :src="product.pic || errorImage" class="product-image" />
                    <div class="product-info">
                        <div class="product-name">{{ product.title }}</div>
                        <div class="product-spec">{{ product.spec || '' }}</div>
                        <div class="product-price">¥{{ product.price.toFixed(2) }} × {{ product.count }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { showToast } from 'vant';

export default {
    data() {
        return {
            order: {},
            selectedMethod: 'wechat',
            isPaying: false,
            paymentSuccess: false,
            errorImage: 'https://picsum.photos/300/300?text=图片加载失败'
        };
    },
    computed: {
        // 计算订单总金额
        orderAmount() {
            let amount = 0;
            if (this.order.products) {
                this.order.products.forEach(item => {
                    amount += item.count * item.price;
                });
            }
            return amount.toFixed(2);
        },
        // 获取支付方式文本描述
        paymentMethodText() {
            const methodMap = {
                'wechat': '微信支付',
                'alipay': '支付宝',
                'card': '银行卡支付'
            };
            return methodMap[this.selectedMethod] || this.selectedMethod;
        },
        // 格式化支付时间
        formattedPaymentTime() {
            if (!this.order.paymentTime) return '';
            const date = new Date(this.order.paymentTime);
            return date.toLocaleString();
        }
    },
    created() {
        this.loadOrderDetails();
    },
    methods: {
        // 加载订单详情
        loadOrderDetails() {
            try {
                const orderId = this.$route.params.orderId;
                const orderHistoryStr = localStorage.getItem('orderHistory');

                if (!orderHistoryStr) {
                    throw new Error('未找到订单历史');
                }

                const orderHistory = JSON.parse(orderHistoryStr);
                const order = orderHistory.find(o => o.id === parseInt(orderId));

                if (!order) {
                    throw new Error('未找到该订单');
                }

                // 核心逻辑：根据订单状态设置界面状态
                if (order.status === 1) {
                    this.paymentSuccess = true;
                    this.selectedMethod = order.paymentMethod || 'wechat';
                }

                this.order = order;
            } catch (error) {
                console.error('加载订单详情失败:', error);
                showToast('订单信息加载失败');
                setTimeout(() => {
                    this.$router.back();
                }, 1500);
            }
        },
        // 处理支付逻辑
        processPayment() {
            // 如果订单已支付，直接返回
            if (this.order.status === 1) {
                return;
            }

            this.isPaying = true;

            // 模拟支付过程
            setTimeout(() => {
                try {
                    // 更新订单状态
                    let orderHistoryStr = localStorage.getItem('orderHistory');
                    const orderHistory = JSON.parse(orderHistoryStr);
                    const orderIndex = orderHistory.findIndex(o => o.id === parseInt(this.order.id));

                    if (orderIndex !== -1) {
                        // 核心修改点：设置订单状态为1（已支付）
                        orderHistory[orderIndex].status = 1;
                        orderHistory[orderIndex].paymentMethod = this.selectedMethod;
                        orderHistory[orderIndex].paymentTime = new Date().toISOString();

                        // 保存到本地存储
                        localStorage.setItem('orderHistory', JSON.stringify(orderHistory));

                        // 更新当前组件中的订单状态
                        this.order = { ...orderHistory[orderIndex] };

                        // 显示支付成功状态
                        this.paymentSuccess = true;

                        // 移除待支付标记
                        localStorage.removeItem('pendingPaymentOrderId');

                        showToast('支付成功');
                    } else {
                        throw new Error('找不到该订单');
                    }
                } catch (error) {
                    console.error('支付处理失败:', error);
                    showToast('支付失败，请稍后再试');
                } finally {
                    this.isPaying = false;
                }
            }, 1500); // 模拟支付延迟
        }, // 修复：添加逗号分隔方法
        // 导航到订单列表
        goToOrderList() {
            this.$router.push({ name: 'orderList' });
        },
        // 导航到首页
        goToHome() {
            this.$router.push({ name: 'home' });
        }
    }
}
</script>

<style lang="less" scoped>
.payment-page {
    background-color: #f8f8f8;
    min-height: 100vh;

    .card {
        background-color: white;
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 15px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .order-summary {
        .order-id {
            color: #666;
            margin-bottom: 10px;
        }

        .amount {
            color: #e64340;
            font-size: 20px;
            font-weight: bold;
        }
    }

    .payment-methods {
        .method-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
        }

        // 为支付方式添加间距
        .van-radio {
            margin-bottom: 15px;

            &:last-child {
                margin-bottom: 0;
            }
        }

        .payment-option {
            display: flex;
            align-items: center;
        }
    }

    .confirm-payment-btn {
        margin-top: 20px;
        height: 50px;
        font-size: 18px;
    }

    .payment-success-message {
        text-align: center;

        .success-icon {
            margin-bottom: 15px;
        }

        .success-text {
            margin-bottom: 20px;
            font-size: 20px;
            color: #07c160;
            font-weight: bold;
        }

        .success-details {
            margin-bottom: 25px;
            text-align: left;

            .detail-item {
                display: flex;
                padding: 8px 0;
                border-bottom: 1px solid #f5f5f5;

                .label {
                    color: #666;
                    width: 90px;
                }

                .value {
                    flex: 1;
                }
            }

            .detail-item:last-child {
                border-bottom: none;
            }
        }

        .action-buttons {
            display: flex;
            gap: 15px;

            .van-button {
                flex: 1;
                height: 48px;
            }
        }
    }

    .products-preview {
        .preview-title {
            font-weight: bold;
            margin-bottom: 15px;
        }

        .product-item {
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid #f5f5f5;

            .product-image {
                width: 60px;
                height: 60px;
                object-fit: cover;
                border-radius: 4px;
            }

            .product-info {
                flex: 1;
                margin-left: 15px;

                .product-name {
                    font-weight: bold;
                    margin-bottom: 5px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    -webkit-box-orient: vertical;
                }

                .product-spec {
                    color: #666;
                    font-size: 12px;
                    margin-bottom: 5px;
                }

                .product-price {
                    color: #e64340;
                }
            }
        }

        .product-item:last-child {
            border-bottom: none;
        }
    }
}
</style>